﻿using System;
using System.Drawing;
using System.Windows.Forms;
using AForge.Video.DirectShow;

namespace zymain
{
    public partial class FrmVideo : Form
    {
        // 设置摄像头参数
        private FilterInfoCollection videoDevices;// 采集所有摄像头
        public bool isVideo = false;
        public FrmVideo()
        {
            InitializeComponent();
        }
        private void ShutCamera()
        {
            if (videoSourcePlayer1.VideoSource != null)
            {
                videoSourcePlayer1.SignalToStop();
                videoSourcePlayer1.WaitForStop();
                videoSourcePlayer1.VideoSource = null;
            }
        }
        private void FrmVideo_Load(object sender, EventArgs e)
        {
            if (!isVideo)
            {
                //枚举视频输入设备
                videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
                if (videoDevices.Count == 0)
                {
                    CameraKay.Text = "没有检测到视频设备！";
                    videoDevices = null;
                }
                foreach (FilterInfo device in videoDevices)
                {
                    CameraKay.Items.Add(device.Name);
                    //CameraKay.Text = device.Name;
                    isVideo = true;
                }
                CameraKay.SelectedIndex = 0;
            }
        }

        private void camera_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (isVideo)
            {
                this.ShutCamera();
                VideoCaptureDevice videoCapture = new VideoCaptureDevice(videoDevices[CameraKay.SelectedIndex].MonikerString);
                videoSourcePlayer1.VideoSource = videoCapture;
                videoSourcePlayer1.Start();
                pzBtn.Enabled = true;
            }
        }

        private void pzBtn_Click(object sender, EventArgs e)
        {
            Bitmap img = videoSourcePlayer1.GetCurrentVideoFrame();//拍摄
            pictureBox1.Image = img;
        }
        private void video_FormCLosing(object sender, FormClosingEventArgs e)
        {
            // 设置拍照关闭代码
            ShutCamera();
            if(pictureBox1.Image!=null)
                DialogResult = DialogResult.OK;
            else
                DialogResult = DialogResult.Cancel;
            e.Cancel = false;
        }
    }
}
